package com.write.program.socket;

import com.alibaba.fastjson.JSONObject;
import com.write.program.socket.message.Message;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Endstart
 * Date: 2019-11-20
 * Time: 23:14
 */
public abstract class SocketService extends Thread {
    protected Socket socket;
    private long lastReceiveTime = System.currentTimeMillis(); //上一次收到消息时间
    private long lastSendTime = System.currentTimeMillis();    //上一次发送消息时间

    public SocketService(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        parseSocketInput();
    }

    /**
     * 实时监控有没消息过来
     */
    protected void parseSocketInput() {
        try {
            // 读取数据
            String str = null;
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while ((str = bufferedReader.readLine()) != null) {
                JSONObject message = JSONObject.parseObject(str);
                receiveMessage(message);
            }
//            System.out.println("-----end---");
        } catch (Exception e) {
//            e.printStackTrace();
        }
    }

    /**
     * 对接收到的各种消息进行解析
     * @param message
     */
    protected void receiveMessage(JSONObject message ) throws IOException{
//        System.out.println("receive: " + message);
        lastReceiveTime = System.currentTimeMillis();
        if (message == null) {
            return;
        }
        Message returnMessage = processReceiveMessage(message);
        sendMessage(returnMessage);
    }

    public abstract Message processReceiveMessage(JSONObject messageObj);


    /**
     * 发送消息
     *
     * @param message
     * @throws IOException
     */
    public void sendMessage(Message message) throws IOException {
        if (message == null) {
            return;
        }
        lastSendTime = System.currentTimeMillis();
//        System.out.println("send: " + message);
        PrintStream out = new PrintStream(socket.getOutputStream());
        out.println(message.toString());
        out.flush();
    }


    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

    public long getLastReceiveTime() {
        return lastReceiveTime;
    }

    public long getLastSendTime() {
        return lastSendTime;
    }

}
